package com.wh.base.sys.cert.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.base.aop.documented.OperLog;
import com.wh.base.sys.cert.controller.form.SearchPageForm;
import com.wh.base.sys.cert.entity.Cert;
import com.wh.base.sys.cert.service.CertService;
import com.wh.base.sys.user.controller.form.UpdateStatusForm;
import com.wh.base.sys.user.service.UserService;
import com.wh.base.util.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.wh.base.sys.cert.controller.form.IdsForm;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Pny
 * @Date 2022/5/20
 */
@Controller
@RequestMapping("/sys/cert")
public class CertController {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

    @Autowired
    private CertService certService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Resource
    private ExcelUtil excelUtil;


    @GetMapping("/index")
    @ApiOperation(value = "首页页面")
    @SaCheckPermission("cert:view")
    public String index(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+ StpUtil.getLoginIdAsLong())); //用户权限
        return "cert/index";
    }


    @PostMapping("/getPage")
    @ApiOperation(value = "分页查询数据")
    @ResponseBody
    @SaCheckLogin
    public R getPage(@Validated SearchPageForm form){
        Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());

        LambdaQueryWrapper<Cert> queryWrapper = new LambdaQueryWrapper();
        if(!StringUtil.isEmpty(form.getName())) {
            queryWrapper.like(Cert::getName, form.getName());
        }
        if(!StringUtil.isEmpty(form.getCardNumber())) {
            queryWrapper.like(Cert::getCardNumber, form.getCardNumber());
        }
        if(!StringUtil.isEmpty(form.getMajor())) {
            queryWrapper.like(Cert::getMajor, form.getMajor());
        }
        if(!StringUtil.isEmpty(form.getLicenceIssued())) {
            queryWrapper.like(Cert::getLicenceIssued, form.getLicenceIssued());
        }
        if(!StringUtil.isEmpty(form.getStatus())) {
            queryWrapper.like(Cert::getStatus, form.getStatus());
        }

        queryWrapper.eq(Cert::getIsDelete,0);

        Page pagelist = certService.page(roadPage,queryWrapper);

        return R.ok().put("page", pagelist);
    }


    @ResponseBody
    @PostMapping("/add")
    @SaCheckPermission("cert:add")
    @OperLog(operModul = "证书管理",operType = "添加",operDesc = "添加证书")
    public R add(Cert cert){
//        前端传过来的身份证，证书名称，证书编号
        String cerd = cert.getCardNumber()+cert.getCertNumber()+cert.getCertPrefix();

        QueryWrapper<Cert> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cerd_number",cert.getCardNumber());

        List<Cert> list = certService.list(queryWrapper);
        for(Cert li: list){
//            数据库查到的身份证，证书名称，证书编号
            String cerd1 = li.getCardNumber()+li.getCertNumber()+li.getCertPrefix();
            if (cerd == cerd1 || cerd.equals(cerd1) ){
                return R.error("该证书已存在！！");
            }
        }

        cert.setCreateTime(new Date());
        cert.setCreateUser(userService.getUser().getUsername());
        certService.save(cert);
        return R.ok();
    }

    @ResponseBody
    @SaCheckPermission("cert:delete")
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable int id){
        certService.removeById(id);
        return R.ok();
    }


    @OperLog(operModul = "证书管理",operType = "修改",operDesc = "修改证书")
    @ResponseBody
    @PostMapping("/update")
    public R update(Cert cert){
        //        前端传过来的身份证，证书名称，证书编号
        String cerd = cert.getCardNumber()+cert.getCertNumber()+cert.getCertPrefix();

        QueryWrapper<Cert> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cerd_number",cert.getCardNumber());

        List<Cert> list = certService.list(queryWrapper);
        for(Cert li: list){
//            数据库查到的身份证，证书名称，证书编号
            String cerd1 = li.getCardNumber()+li.getCertNumber()+li.getCertPrefix();
            if (cerd == cerd1 || cerd.equals(cerd1) ){
                return R.error("该证书已存在！！");
            }
        }
        cert.setUpdateTime(new Date());
        cert.setUpdateUser(userService.getUser().getUsername());
        certService.update(cert);
        return R.ok();
    }



    @GetMapping("/recycleIndex")
    @ApiOperation(value = "回收站页面")
    @SaCheckPermission("cert:recycle")
    public String recycleIndex(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+StpUtil.getLoginIdAsLong())); //用户权限
        return "cert/recycle";
    }

    @PostMapping("/recycle")
    @ApiOperation(value = "根据id集合将数据放入回收站")
    @SaCheckPermission("cert:recycle")
    @ResponseBody
    @OperLog(operModul = "证书管理", operType = "放入回收站" ,operDesc = "将证书放入回收站")
    public R recycle(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Cert> certList = new ArrayList<>();
            for(Long id : idList) {
                Cert cert = new Cert();
                cert.setId(id);
                cert.setIsDelete(1);
                cert.setUpdateTime(new Date());
                cert.setUpdateUser(userService.getUser().getUsername());
                certList.add(cert);

            }

            certService.saveOrUpdateBatch(certList);
        }
        return R.ok("删除成功");
    }

    @OperLog(operModul = "证书管理",operType = "恢复数据",operDesc = "恢复放在回收站的证书")
    @PostMapping("/restore")
    @ApiOperation(value = "根据ids批量还原回收站的数据")
    @SaCheckPermission("cert:recycle")
    @ResponseBody
    public R restore(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Cert> certList = new ArrayList<>();
            for(Long id : idList) {
                Cert cert = new Cert();
                cert.setId(id);
                cert.setUpdateTime(new Date());
                cert.setIsDelete(0);
                certList.add(cert);
            }
            if(certList.size() > 0) {
                certService.saveOrUpdateBatch(certList);
            }
        }
        return R.ok("还原成功");
    }



    @PostMapping("/getRecyclePage")
    @ApiOperation(value = "分页查询回收站数据")
    @ResponseBody
    @SaCheckPermission("cert:recycle")
    public R getRecyclePage(@Validated SearchPageForm form){
        Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
        LambdaQueryWrapper<Cert> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(Cert::getIsDelete, 1);

        Page pageList = certService.page(roadPage, queryWrapper);
        return R.ok().put("page", pageList);
    }

    @PostMapping("/uptStatus")
    @ApiOperation(value = "修改状态")
    @ResponseBody
    @OperLog(operModul = "证书管理", operType = "修改状态" ,operDesc = "修改证书状态")
    public R uptStatus(@Validated UpdateStatusForm form){
        Cert cert = new Cert();
        cert.setStatus(form.getStatus());
        cert.setId(form.getId());
        certService.saveOrUpdate(cert);
        return R.ok("修改成功");
    }

    @PostMapping("/delete")
    @ApiOperation(value = "根据id集合彻底删除数据")
    @SaCheckPermission("cert:delete")
    @ResponseBody
    @OperLog(operModul = "证书管理", operType = "彻底删除" ,operDesc = "彻底删除证书")
    public R delete(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            certService.removeByIds(idList);
        }
        return R.ok("删除成功");
    }


    //    导入Excel
    @SaCheckPermission("cert:view")
    @PostMapping ("/excel")
    @ResponseBody
    @OperLog(operModul = "证书上传Excel",operType = "批量上传",operDesc = "批量上传证书")
    public R importExcel(@RequestParam("file") MultipartFile file) throws Exception {

        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
//        通过读取Excel的工具类得到表格的数据
        List<List<Object>> bankListByExcel = excelUtil.getBankListByExcel(inputStream, filename);
        List<Object> objects = null;

        Cert cert = null;

//        遍历表格数据得到单个证书
        for (int i = 0; i < bankListByExcel.size(); i++) {

            objects = bankListByExcel.get(i);
            cert = new Cert();
//            遍历证书，得到每个单元格的数据
            for (int j = 0; j < objects.size(); j++) {

                String o = (String)objects.get(j);
                if (j == 0){
                    cert.setName(o);
                }
                if (j == 1){
                    cert.setCardNumber(o);
                }
                if (j == 2){
                    cert.setMajor(o);
                }
                if (j == 3){
                    int period = (int)Double.parseDouble(o);
                    System.out.println(period);
                    cert.setPeriod(period);
                }
                if (j == 4){
                    cert.setLicenceIssued(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }
                if (j == 5){
                    cert.setCertPrefix(o);
                }
                if (j == 6){

                    if (o.contains(".")){
                        String substring = o.substring(0, o.indexOf("."));
                        cert.setCertNumber(substring);
                    }
                    cert.setCertNumber(o);
                }
                if (j == 7){
                    cert.setStartTime(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }
                if (j == 8){
                    cert.setEndTime(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }
            }
            cert.setCreateTime(new Date());
            cert.setCreateUser(userService.getUser().getUsername());
            certService.save(cert);
        }
        return R.ok("批量导入成功！");
    }

    //    预览证书
    @SaCheckLogin
    @PostMapping("/preview/{id}")
    @OperLog(operModul = "证书预览",operType = "证书预览",operDesc = "证书预览")
    public String preview(@PathVariable int id, HttpServletRequest request){
        Cert cert = certService.getById(id);
        String stime = simpleDateFormat.format(cert.getStartTime());
        String etime = simpleDateFormat.format(cert.getEndTime());
        String litime = simpleDateFormat.format(cert.getLicenceIssued());
        request.setAttribute("cert",cert);
        request.setAttribute("stime",stime);
        request.setAttribute("etime",etime);
        request.setAttribute("litime",litime);
        return "cert/cert";
    }

}
